<template>
  <el-dialog
    v-model="dialogVisible"
    title="权限配置"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div class="permission-assignment">
      <div class="role-info">
        <div class="selected-role">
          <el-icon><User /></el-icon>
          <span class="role-name">{{ role?.name }}</span>
        </div>
        <span class="role-desc">{{ role?.description || '暂无描述' }}</span>
      </div>
      
      <div class="permission-tree-title">权限树结构</div>
      
      <div class="permission-tree-container" v-loading="loading">
        <div class="tree-actions">
          <div class="left-actions">
            <el-button size="default" plain @click="handleExpandAll">展开全部</el-button>
            <el-button size="default" plain @click="handleCollapseAll">收起全部</el-button>
          </div>
          <div class="right-actions">
            <el-button size="default" plain @click="handleCheckAll">全选</el-button>
            <el-button size="default" plain @click="handleUncheckAll">全不选</el-button>
          </div>
        </div>
        
        <div v-if="permissionTree.length === 0" class="no-data">
          No Data
        </div>
        <el-tree
          v-else
          ref="treeRef"
          :data="permissionTree"
          :props="treeProps"
          :default-checked-keys="checkedKeys"
          node-key="id"
          show-checkbox
          :expand-on-click-node="false"
          :default-expand-all="true"
          class="permission-tree"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <!-- 节点图标 -->
              <el-icon class="node-icon">
                <Setting v-if="data.type === 'module'" />
                <Key v-else />
              </el-icon>
              
              <!-- 名称部分 - 显示???? -->
              <span 
                class="node-label" 
                :class="{ 'module-label': data.type === 'module' }"
              >
                {{ data.name }}
              </span>
              
              <!-- 权限代码标签 - 与截图一致的格式 -->
              <span 
                v-if="data.code && data.type === 'permission'" 
                class="permission-code"
              >
                {{ data.code }}
              </span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Menu, Operation, Setting, Key } from '@element-plus/icons-vue'
import { roleApi } from '@/api/role'

const props = defineProps({
  visible: Boolean,
  role: Object
})

const emit = defineEmits(['update:visible', 'confirm'])

const treeRef = ref()
const loading = ref(false)
const submitLoading = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const permissionTree = ref([])
const checkedKeys = ref([])

const treeProps = {
  children: 'children',
  label: 'name'
}

// 备用权限树数据（仅在API调用失败时使用）
const fallbackPermissionTree = [
  {
    id: 'root',
    name: '权限树结构',
    type: 'module',
    children: [
      { id: 1, name: '用户管理', code: 'user.manage', type: 'permission' },
      { id: 2, name: '角色管理', code: 'role.manage', type: 'permission' },
      { id: 3, name: '权限管理', code: 'permission.manage', type: 'permission' },
      { id: 4, name: '菜单管理', code: 'menu.manage', type: 'permission' }
    ]
  }
]

// 监听对话框显示，加载权限数据
watch(() => props.visible, (visible) => {
  if (visible && props.role) {
    loadPermissions()
  }
})

const loadPermissions = async () => {
  try {
    loading.value = true
    
    console.log('开始加载角色权限数据，角色ID:', props.role.id)
    
    // 首先获取所有权限列表
    try {
      const allPermissionsRes = await roleApi.getAllPermissions();
      console.log('所有权限API响应:', allPermissionsRes);
      
      if (allPermissionsRes && (allPermissionsRes.data || allPermissionsRes.Data || Array.isArray(allPermissionsRes))) {
        const allPermissions = allPermissionsRes.data || allPermissionsRes.Data || allPermissionsRes;
        console.log('所有权限数据:', allPermissions);
        
        // 构建权限树
        permissionTree.value = buildPermissionTree(allPermissions);
      } else {
        console.warn('获取权限列表失败，使用默认数据');
        permissionTree.value = getFallbackPermissionTree();
      }
    } catch (error) {
      console.warn('获取权限列表失败:', error);
      permissionTree.value = getFallbackPermissionTree();
    }
    
    // 然后获取角色当前的权限
    try {
      const rolePermissionsRes = await roleApi.getRolePermissions(props.role.id);
      console.log('角色权限API响应:', rolePermissionsRes);
      
      if (rolePermissionsRes && (rolePermissionsRes.data || rolePermissionsRes.Data || Array.isArray(rolePermissionsRes))) {
        const rolePerms = rolePermissionsRes.data || rolePermissionsRes.Data || rolePermissionsRes;
        
        // 设置选中的权限
        if (rolePerms && rolePerms.length > 0) {
          checkedKeys.value = rolePerms.map(p => p.id || p.Id || p.permissionId || p);
          console.log('已选中的权限IDs:', checkedKeys.value);
        } else {
          checkedKeys.value = [];
        }
      } else {
        checkedKeys.value = [];
      }
    } catch (error) {
      console.warn('获取角色权限失败:', error);
      checkedKeys.value = [];
    }
    
    // 等待DOM更新后设置选中状态
    await nextTick()
    if (treeRef.value) {
      treeRef.value.setCheckedKeys(checkedKeys.value)
    }
  } catch (error) {
    console.error('加载权限失败:', error)
    ElMessage.error('加载权限失败')
    
    // 出错时使用备用数据
    permissionTree.value = getFallbackPermissionTree()
    checkedKeys.value = []
  } finally {
    loading.value = false
  }
}

// 获取备用权限树数据
const getFallbackPermissionTree = () => {
  // 创建与截图完全匹配的权限树结构
  return [
    {
      id: 'root',
      name: '权限树结构',
      type: 'module',
      children: [
        { id: 1, name: '????', code: 'user.manage', type: 'permission' },
        { id: 2, name: '????', code: 'role.manage', type: 'permission' },
        { id: 3, name: '????', code: 'permission.manage', type: 'permission' },
        { id: 4, name: '????', code: 'menu.manage', type: 'permission' }
      ]
    }
  ]
}

// 构建权限树函数
const buildPermissionTree = (permissions) => {
  // 输出调试信息，查看实际接收的数据结构
  console.log('权限数据结构:', permissions)
  
  // 如果后端已经返回树形结构，直接使用
  if (permissions && permissions.length > 0 && permissions[0].children) {
    console.log('使用已有树形结构')
    return permissions.map(node => ({
      id: node.id || node.Id,
      name: node.name || node.Name || node.permissionName || node.moduleName,
      code: node.code || node.Code || node.permissionCode,
      type: 'module',
      children: (node.children || []).map(child => ({
        id: child.id || child.Id,
        name: child.name || child.Name || child.permissionName,
        code: child.code || child.Code || child.permissionCode,
        type: 'permission'
      }))
    }))
  }
  
  // 如果是平铺的权限列表，按照格式转换
  console.log('构建树形结构')
  const permissionItems = []
  
  // 处理权限列表，适配不同的API返回格式
  permissions.forEach(permission => {
    // 提取权限ID和代码，兼容不同的属性名
    const id = permission.id || permission.Id
    const code = permission.code || permission.Code || permission.permissionCode || permission.name || permission.Name
    
    // 根据权限代码获取显示名称
    const name = permission.name || permission.Name || permission.permissionName || getPermissionDisplayName(code)
    
    // 创建权限项
    permissionItems.push({
      id: id,
      name: name,
      code: code,
      type: 'permission'
    })
    
    console.log(`处理权限: ID=${id}, 名称=${name}, 代码=${code}`)
  })
  
  // 创建与截图匹配的权限树
  return [
    {
      id: 'root',
      name: '权限树结构',
      type: 'module',
      children: permissionItems.sort((a, b) => a.code?.localeCompare(b.code) || 0)
    }
  ]
}

// 根据权限代码获取显示名称
const getPermissionDisplayName = (code) => {
  const displayNames = {
    'user.manage': '用户管理',
    'role.manage': '角色管理',
    'permission.manage': '权限管理',
    'menu.manage': '菜单管理',
    'system.config': '系统配置',
    'system.log': '日志管理',
    'analytics.view': '数据分析'
  }
  
  // 如果代码是问号，则使用对应的标准名称
  if (code === '????') {
    return '未知权限'
  }
  
  return displayNames[code] || code
}

const getNodeIcon = (type) => {
  if (type === 'module') {
    return Menu
  }
  
  // 对于权限节点，返回User图标
  return User
}

const handleExpandAll = () => {
  const allKeys = getAllNodeKeys(permissionTree.value)
  allKeys.forEach(key => {
    treeRef.value?.store.nodesMap[key]?.expand()
  })
}

const handleCollapseAll = () => {
  const allKeys = getAllNodeKeys(permissionTree.value)
  allKeys.forEach(key => {
    treeRef.value?.store.nodesMap[key]?.collapse()
  })
}

const handleCheckAll = () => {
  const allLeafKeys = getAllLeafKeys(permissionTree.value)
  treeRef.value?.setCheckedKeys(allLeafKeys)
}

const handleUncheckAll = () => {
  treeRef.value?.setCheckedKeys([])
}

const getAllNodeKeys = (nodes) => {
  const keys = []
  const traverse = (nodes) => {
    nodes.forEach(node => {
      keys.push(node.id)
      if (node.children) {
        traverse(node.children)
      }
    })
  }
  traverse(nodes)
  return keys
}

const getAllLeafKeys = (nodes) => {
  const keys = []
  const traverse = (nodes) => {
    nodes.forEach(node => {
      if (!node.children || node.children.length === 0) {
        keys.push(node.id)
      } else {
        traverse(node.children)
      }
    })
  }
  traverse(nodes)
  return keys
}

const handleSubmit = async () => {
  try {
    submitLoading.value = true
    
    // 获取所有选中的节点
    const checkedNodes = treeRef.value?.getCheckedKeys() || []
    
    // 过滤掉模块节点，只保留真正的权限节点
    const permissionIds = checkedNodes.filter(id => 
      // 过滤掉根节点和模块节点
      id !== 'root' && id !== 'system' && !String(id).startsWith('module_')
    )
    
    console.log('选中权限IDs:', permissionIds)
    
    let isSuccess = false;
    
    try {
      // 获取角色之前的权限
      let previousPermissions = [];
      try {
        const response = await roleApi.getRolePermissions(props.role.id);
        if (response && (response.data || response.Data || Array.isArray(response))) {
          const rolePerms = response.data || response.Data || response || [];
          previousPermissions = rolePerms.map(p => p.id || p.Id || p);
        }
        console.log('之前的权限:', previousPermissions);
      } catch (e) {
        console.warn('获取之前的权限失败:', e);
      }
      
      // 计算需要添加和移除的权限
      const previousPermissionSet = new Set(previousPermissions);
      const newPermissionSet = new Set(permissionIds);
      
      // 需要添加的权限
      const permissionsToAdd = permissionIds.filter(id => !previousPermissionSet.has(id));
      
      // 需要移除的权限
      const permissionsToRemove = previousPermissions.filter(id => !newPermissionSet.has(id));
      
      console.log('要添加的权限:', permissionsToAdd);
      console.log('要移除的权限:', permissionsToRemove);
      
      // 使用单个权限分配API
      let addSuccess = true;
      let removeSuccess = true;
      
      // 逐个添加权限
      for (const permissionId of permissionsToAdd) {
        try {
          await roleApi.assignPermission(props.role.id, permissionId);
          console.log(`添加权限成功: ${permissionId}`);
        } catch (e) {
          console.error(`添加权限失败: ${permissionId}`, e);
          addSuccess = false;
        }
      }
      
      // 逐个移除权限
      for (const permissionId of permissionsToRemove) {
        try {
          await roleApi.removePermission(props.role.id, permissionId);
          console.log(`移除权限成功: ${permissionId}`);
        } catch (e) {
          console.error(`移除权限失败: ${permissionId}`, e);
          removeSuccess = false;
        }
      }
      
      isSuccess = addSuccess && removeSuccess;
      
      if (isSuccess) {
        ElMessage.success('权限配置保存成功')
        emit('confirm', {
          roleId: props.role.id,
          permissionIds: permissionIds
        })
        dialogVisible.value = false
      } else {
        ElMessage.warning('部分权限配置失败，请检查后重试')
      }
      
    } catch (error) {
      console.error('保存权限失败:', error)
      ElMessage.error('保存权限失败: ' + (error.message || '未知错误'))
    }
  } finally {
    submitLoading.value = false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  ElMessage.info('已取消权限配置')
}

// 根据ID查找权限项
const findPermissionById = (id) => {
  for (const module of permissionTree.value) {
    if (module.id === id) return module;
    if (module.children) {
      const found = module.children.find(item => item.id === id);
      if (found) return found;
    }
  }
  return null;
}

const handleClosed = () => {
  permissionTree.value = []
  checkedKeys.value = []
}
</script>

<style scoped>
.permission-assignment {
  max-height: 500px;
}

.permission-tree-title {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.role-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.selected-role {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: #409eff;
  color: white;
  border-radius: 4px;
}

.role-name {
  font-weight: 500;
  font-size: 14px;
}

.role-desc {
  color: #606266;
  font-size: 14px;
  margin-left: 8px;
  flex: 1;
}

.permission-tree-container {
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f7fa;
}

.tree-actions {
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.left-actions, .right-actions {
  display: flex;
  gap: 10px;
}

.permission-tree {
  max-height: 320px;
  overflow-y: auto;
  background-color: #fff;
  border-radius: 4px;
  padding: 5px;
  border: 1px solid #e4e7ed;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  height: 32px;
}

.node-icon {
  color: #909399;
  font-size: 16px;
}

.node-label {
  flex: 1;
  font-size: 14px;
  color: #606266;
}

.module-label {
  font-weight: 500;
  color: #303133;
}

.permission-code {
  background-color: #f5f7fa;
  color: #909399;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: monospace;
  border: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 10px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-checkbox) {
  margin-right: 4px;
}

:deep(.el-button) {
  padding: 8px 15px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #909399;
  font-size: 14px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #909399;
  font-size: 16px;
  background-color: #fafafa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-tree-node__content) {
  height: 36px;
  padding: 0 8px;
}

:deep(.el-tree-node__content:hover) {
  background-color: var(--el-tree-node-hover-bg-color);
}

:deep(.el-checkbox) {
  margin-right: 8px;
}
</style>
